import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../app_views.dart';

class LoginView extends GetView<AuthLogic> {
  const LoginView({super.key});

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Get.back();
        return false;
      },
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: LayoutBuilder(
          builder: (_, constraints) {
            final isWide = constraints.maxWidth > 600;
            return Container(
              decoration: const BoxDecoration(
                gradient: LinearGradient(
                  colors: [Color(0xFFF1F5FF), Color(0xFFFDF2E2)],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
              ),
              child: SafeArea(
                child: Stack(
                  children: [
                    // 返回按钮
                    Positioned(
                      top: 8,
                      left: 8,
                      child: IconButton(
                        icon: const Icon(Icons.arrow_back),
                        onPressed: () => Get.back(),
                      ),
                    ),
                    // 主体内容
                    Center(
                      child: SingleChildScrollView(
                        padding: const EdgeInsets.all(20),
                        child: ConstrainedBox(
                          constraints:
                              BoxConstraints(maxWidth: isWide ? 520 : 380),
                          child: Obx(() {
                            final state = controller.state.value;
                            return Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Text(
                                  '星命之境',
                                  style:
                                      Theme.of(context).textTheme.displayLarge,
                                ),
                                const SizedBox(height: 8),
                                Text(
                                  '开启你的命盘旅程',
                                  style:
                                      Theme.of(context).textTheme.titleMedium,
                                ),
                                const SizedBox(height: 28),
                                _buildModeToggle(state),
                                const SizedBox(height: 24),
                                Container(
                                  padding: EdgeInsets.symmetric(
                                    horizontal: isWide ? 32 : 20,
                                    vertical: isWide ? 32 : 24,
                                  ),
                                  decoration: BoxDecoration(
                                    color: AppColors.backgroundCard,
                                    borderRadius: BorderRadius.circular(24),
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.black.withOpacity(0.08),
                                        blurRadius: 20,
                                        offset: const Offset(0, 12),
                                      ),
                                    ],
                                    border: Border.all(
                                      color: Colors.white.withOpacity(0.6),
                                    ),
                                  ),
                                  child: Column(
                                    children: [
                                      if (state.isSmsLogin)
                                        _buildPhoneLogin(state)
                                      else
                                        _buildEmailLogin(state),
                                      if (state.errorMessage != null) ...[
                                        const SizedBox(height: 16),
                                        Text(
                                          state.errorMessage!,
                                          style: const TextStyle(
                                              color: Colors.redAccent),
                                        ),
                                      ],
                                      const SizedBox(height: 28),
                                      SizedBox(
                                        width: double.infinity,
                                        child: ElevatedButton(
                                          onPressed: state.isLoading
                                              ? null
                                              : controller.login,
                                          child: state.isLoading
                                              ? const SizedBox(
                                                  height: 18,
                                                  width: 18,
                                                  child:
                                                      CircularProgressIndicator(
                                                    strokeWidth: 2,
                                                  ),
                                                )
                                              : const Text('立即登录'),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                const SizedBox(height: 16),
                                TextButton(
                                  onPressed: () {
                                    controller.clearAllInputs(); // 清空输入
                                    Get.toNamed('/auth/register');
                                  },
                                  child: const Text('没有账号？点击注册'),
                                ),
                                const SizedBox(height: 24),
                                Divider(color: Colors.black.withOpacity(0.1)),
                                const SizedBox(height: 16),
                                Column(
                                  children: [
                                    OutlinedButton.icon(
                                      onPressed: () {
                                        // 微信登录功能暂未实现
                                        Get.snackbar(
                                          '提示',
                                          '微信登录功能即将上线',
                                          snackPosition: SnackPosition.TOP,
                                        );
                                      },
                                      icon: const Icon(Icons.wechat,
                                          color: Colors.green),
                                      label: const Text('微信登录'),
                                    ),
                                    const SizedBox(height: 8),
                                    const Text(
                                      '未来将支持微信快速登录',
                                      style: TextStyle(
                                        color: AppColors.textSecondaryLight,
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            );
                          }),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildModeToggle(AuthState state) {
    return SegmentedButton<bool>(
      segments: const [
        ButtonSegment<bool>(
          value: true,
          label: Text('手机号验证码登录'),
          icon: Icon(Icons.phone_android),
        ),
        ButtonSegment<bool>(
          value: false,
          label: Text('邮箱密码登录'),
          icon: Icon(Icons.email_outlined),
        ),
      ],
      selected: {state.isSmsLogin},
      onSelectionChanged: (value) => controller.toggleLoginMode(value.first),
    );
  }

  Widget _buildPhoneLogin(AuthState state) {
    return Column(
      children: [
        TextField(
          controller: TextEditingController(text: state.phone)
            ..selection = TextSelection.collapsed(offset: state.phone.length),
          keyboardType: TextInputType.phone,
          onChanged: controller.onPhoneChanged,
          decoration: InputDecoration(
            labelText: '手机号',
            hintText: '请输入 11 位大陆手机号码',
            prefixIcon: const Icon(Icons.phone),
            errorText: state.phoneError,
          ),
        ),
        const SizedBox(height: 18),
        TextField(
          controller: TextEditingController(text: state.phoneSmsCode)
            ..selection =
                TextSelection.collapsed(offset: state.phoneSmsCode.length),
          keyboardType: TextInputType.number,
          onChanged: controller.onPhoneSmsCodeChanged,
          decoration: InputDecoration(
            labelText: '短信验证码',
            hintText: '请输入 6 位验证码',
            prefixIcon: const Icon(Icons.sms),
            errorText: state.phoneSmsError,
            suffixIcon: TextButton(
              onPressed: state.phoneSmsCountdown > 0
                  ? null
                  : (state.phoneError == null && state.phone.isNotEmpty)
                      ? controller.requestSmsCode
                      : null,
              child: Text(
                state.phoneSmsCountdown > 0
                    ? '${state.phoneSmsCountdown}s'
                    : '获取验证码',
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildEmailLogin(AuthState state) {
    return Column(
      children: [
        TextField(
          controller: TextEditingController(text: state.email)
            ..selection = TextSelection.collapsed(offset: state.email.length),
          keyboardType: TextInputType.emailAddress,
          onChanged: controller.onEmailChanged,
          decoration: InputDecoration(
            labelText: '邮箱',
            prefixIcon: const Icon(Icons.email),
            errorText: state.emailError,
          ),
        ),
        const SizedBox(height: 18),
        TextField(
          controller: TextEditingController(text: state.emailPassword)
            ..selection =
                TextSelection.collapsed(offset: state.emailPassword.length),
          obscureText: true,
          onChanged: controller.onEmailPasswordChanged,
          decoration: InputDecoration(
            labelText: '密码',
            prefixIcon: const Icon(Icons.lock),
            errorText: state.emailPasswordError,
          ),
        ),
      ],
    );
  }
}